package org.wxd.media.engine;

import com.mongodb.gridfs.GridFSDBFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.wxd.media.api.DownloadCallback;
import org.wxd.media.api.MediaQueryService;
import org.wxd.media.api.exception.MediaCenterException;
import org.wxd.media.api.record.MediaRecord;
import org.wxd.media.domain.GridFsHelper;
import org.wxd.media.domain.Media;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by wangxd on 2016/11/2.
 */
@Service
public class MediaQueryServiceImpl implements MediaQueryService{
    private static final Logger LOOGER = LoggerFactory.getLogger(MediaQueryServiceImpl.class);
    @Autowired
    GridFsTemplate template;

    @Override
    public MediaRecord ofMediaId(String mediaId) {
        Assert.notNull(mediaId,"mediaId must not null.");
        return MediaHelper.asRecord(
                GridFsHelper.asEntity(
                        template.findOne(Query.query(Criteria.where(Media.ID).is(mediaId)))
                ));


    }

    @Override
    public void downLoad(String mediaId, DownloadCallback downLoadAction) {
        GridFSDBFile fsdbFile = template.findOne(Query.query(Criteria.where(Media.ID).is(mediaId)));
        if (fsdbFile == null) return ;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            fsdbFile.writeTo(out);
            downLoadAction.call(fsdbFile.getFilename(),fsdbFile.getContentType(),out.toByteArray(),fsdbFile.getMetaData().toMap());
        } catch (IOException e) {
            LOOGER.info(e.getMessage(),e);
            throw new MediaCenterException(e.getMessage(),e);
        }
    }
}
